<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表卡片 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="10"
          ><div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              v-model="page.query"
              clearable
              @clear="clear"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="search"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="6"
          ><div class="grid-content bg-purple">
            <el-button type="primary" @click="addUser">添加用户</el-button>
          </div></el-col
        >
      </el-row>
      <!-- 添加用户的对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogFormVisible"
        show-close
        @close="closeDialog"
      >
        <el-form
          :model="user"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="user.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="user.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="user.mobile"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addSubmit">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 用户列表 -->
      <el-table :data="userList" stripe style="width: 100%">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changeSwitch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-tooltip content="编辑用户" placement="top">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="edit(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除用户" placement="top">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="del(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 显示分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="page.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalpage"
    >
    </el-pagination>
    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      show-close
      @close="closeEditDialog"
    >
      <el-form
        :model="editUsers"
        :rules="editRules"
        ref="editRuleForm"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUsers.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUsers.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUsers.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      show-close
      @close="closeSetRoleDialog"
    >
      <div class="mgY-20">当前的用户: {{ userinfo.username }}</div>
      <div class="mgY-20">当前的角色: {{ userinfo.role_name }}</div>
      <!-- 下拉选择框选择分配的角色 -->
      分配新角色: <el-select v-model="selectedRoleId" placeholder="请选择">
        <el-option
          v-for="item in rolesList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getUsers();
  },
  data() {
    return {
      page: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      totalpage: 0,
      //   添加用户的名单
      user: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //   对话框是否可视
      dialogFormVisible: false,

      // 添加用户的规则
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "用户名长度在5~10为之间",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            min: 6,
            max: 12,
            message: "密码长度在6~12为之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,
            message: "请输入正确邮箱",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "请输入正确手机号",
            trigger: "blur",
          },
        ],
      },
      // 修改用户对话框是否可视
      editDialogVisible: false,
      // 修改用户初获得用户数据
      editUsers: {
        mobile: "",
        email: "",
      },
      // 修改用户信息的规则
      editRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,
            message: "请输入正确邮箱",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "请输入正确手机号",
            trigger: "blur",
          },
        ],
      },
      // 控制分配角色对话框是否可视
      setRoleDialogVisible: false,
      rolesList: [],
      userinfo: {},
      // 下拉选项框选中的值
      selectedRoleId:''
    };
  },
  methods: {
    // 获取用户信息列表
    async getUsers() {
      let { data: res } = await this.$axios.get("users", {
        params: this.page,
      });
      if (res.meta.status != 200)
        return this.$messages.error("获取用户列表数据失败");
      this.userList = res.data.users;
      this.totalpage = res.data.total;
      this.page.pagenum = res.data.pagenum;
    },
    // 状态改变,数据库改变
    async changeSwitch(userinfo) {
      let { data: res } = await this.$axios.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status == 200) return this.$message.success("修改状态成功");
      this.$message.error("修改状态失败");
      userinfo.mg_state = !userinfo.mg_state;
    },
    // 搜索用户
    search() {
      this.getUsers();
    },
    // 清除搜索框后自动搜索第一页数据
    clear() {
      this.getUsers();
    },
    // 分页上pagesize变化
    handleSizeChange(value) {
      this.page.pagesize = value;
      this.getUsers();
    },
    // 当前页码发生变化
    handleCurrentChange(value) {
      this.page.pagenum = value;
      this.getUsers();
    },
    // 点击添加用户弹出对话框
    addUser() {
      this.dialogFormVisible = true;
    },
    // 对话框关闭,将对话框中的信息清除
    closeDialog() {
      this.$refs.ruleForm.resetFields();
    },
    // 提交对话框信息,添加新用户
    addSubmit() {
      // 先全部进行一次验证
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$axios.post("users", this.user);
        if (res.meta.status != 201) return this.$message.error("用户添加失败");
        this.$message.success("用户添加成功");
        this.dialogFormVisible = false;
      });
    },
    // 点击编辑按钮后，弹出编辑对话框
    async edit(id) {
      this.editDialogVisible = true;
      // 对初始用户数据进行渲染
      let { data: res } = await this.$axios.get("users/" + id);
      if (res.meta.status == 200) {
        this.editUsers = res.data;
      }
    },
    // 关闭对话框的回调事件
    closeEditDialog() {
      this.$refs.editRuleForm.resetFields();
    },
    // 提交修改后的用户信息
    editSubmit() {
      // 先对输入框整体校验一次
      this.$refs.editRuleForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$axios.put(
          "users/" + this.editUsers.id,
          {
            id: this.editUsers.id,
            email: this.editUsers.email,
            mobile: this.editUsers.mobile,
          }
        );
        if (res.meta.status != 200) return this.$message.error("更新用户失败");
        this.$message.success("更新用户成功");
        this.editDialogVisible = false;
        // 更新用户成功后还需更新整个用户列表
        this.getUsers();
      });
    },
    // 点击删除按钮
    async del(id) {
      // 提示框询问是否删除
      let res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (res == "confirm") {
        // 点击确定后发送用户信息到后台
        let { data: response } = await this.$axios.delete("users/" + id);
        if (response.meta.status != 200)
          return this.$message.error("删除用户信息失败");
        this.$message.success("删除用户信息成功");
        // 刷新列表数据
        this.page.pagenum = 1;
        this.getUsers();
      } else {
        this.$message("已取消删除用户");
      }
    },
    // 点击分配角色按钮
    async setRole(role) {
      this.setRoleDialogVisible=true
      this.userinfo = role;
      // 先获取角色列表渲染数据
      let {data:res}=await this.$axios.get("/roles")
      if(res.meta.status!=200)return this.$message.error("获取数据失败")
      this.rolesList=res.data
      
    },
    async setRoleSubmit(){
      // 提交前要先检查一遍用户是否选择
      if(!this.selectedRoleId)return this.$message.error("未选择要分配的角色")
      let {data:resp}=await this.$axios.put(`users/${this.userinfo.id}/role`,{rid:this.selectedRoleId})
      if(resp.meta.status!=200)return this.$message.error("更新失败")
      this.$message.success("更新成功")
      this.setRoleDialogVisible=false
      this.getUsers()
    },
    closeSetRoleDialog(){
      // 关闭时对数据进行重置
      this.userinfo={}
      this.selectedRoleId=''
    }
  },
};
</script>
<style lang="less" scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 100%;
}
.el-card {
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1) !important;
}
.el-form {
  width: 90%;
}
.mgY-20{
  margin: 20px 0;
}
</style>